//@author A0099223B

import java.util.ArrayList;

class AddParser extends Parser {

	private static final String MESSAGE_MISSING_TITLE = "Task's title is missing!";
	private static final ArrayList<String> UNUSABLE_TAGS = new ArrayList<String>() {
		{
			add(TAG_ID);
			add(TAG_KEYWORD);
			add(TAG_DONE);
			add(TAG_NOTDONE);
			add(TAG_TITLE);
		}
	};

	protected static Command parse(String userInput)
			throws InvalidInputException {
		assert (userInput.toLowerCase().startsWith(COMMAND_ADD));

		AddCommand addCommand = new AddCommand();

		if (isSingleWord(userInput)) {
			setAsPopupOpenCommand(addCommand);
		} else {
			setAsTaskAddingCommand(addCommand, userInput);
		}

		return addCommand;
	}

	private static void setAsPopupOpenCommand(AddCommand addCommand) {
		addCommand.isGuiOpenCommand = true;
	}

	private static void setAsTaskAddingCommand(AddCommand addCommand,
			String userInput) throws InvalidInputException {
		ArrayList<String> unparsedWords = getWordsInCommandDetails(userInput);

		addCommand.task = new Task();
		addCommand.task.title = extractTaskTitle(unparsedWords);
		if (!unparsedWords.isEmpty()) {
			checkTags(unparsedWords);
			fillTaskDetails(addCommand.task, unparsedWords);
			checkForReversedDates(addCommand.task.startTime,
					addCommand.task.endTime);
		}

	}

	private static String extractTaskTitle(ArrayList<String> unparsedWords)
			throws InvalidInputException {
		String title = extractWordsBeforeNextTag(unparsedWords);
		checkForEmptyTitle(title);
		return title;
	}

	private static void checkForEmptyTitle(String title)
			throws InvalidInputException {
		if (isEmptyString(title)) {
			throw new InvalidInputException(MESSAGE_MISSING_TITLE);
		}

	}

	private static void checkTags(ArrayList<String> unparsedWords)
			throws InvalidInputException {

		checkForUnusableStringTags(UNUSABLE_TAGS, unparsedWords, COMMAND_ADD);
		checkForRepeatingTags(unparsedWords);
	}

	private static void fillTaskDetails(Task task,
			ArrayList<String> unparsedWords) throws InvalidInputException {

		while (!unparsedWords.isEmpty()) {
			String tag = removeFirstWordFromArray(unparsedWords);

			if (isTaggedAsProject(tag)) {
				task.project = getProjectName(tag);
			} else {
				switchToCorrectAttribute(task, unparsedWords, tag);
			}
		}

	}

	private static void switchToCorrectAttribute(Task task,
			ArrayList<String> unparsedWords, String tag)
			throws InvalidInputException {
		checkIfTag(tag);

		String value = extractWordsBeforeNextTag(unparsedWords);

		checkForEmptyValue(value, tag);
		switch (tag.toLowerCase()) {
		case TAG_START_TIME:
			task.startTime = parseTime(value, TAG_START_TIME);
			break;
		case TAG_END_TIME:
			task.endTime = parseTime(value, TAG_END_TIME);
			break;
		case TAG_PLACE:
			task.place = value;
			break;
		case TAG_DESCRIPTION:
			task.description = value;
			break;
		}

	}

}
